package cn.tianyigps.tianyigpspublic.util;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;

/**
 * Created with IDEA
 *
 * @description: 格式化类
 * @author: cui.guibin
 * @create: 2019/3/21 19:49
 **/
public class FormatUtil {

    private static final ThreadLocal<SimpleDateFormat> DF = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    /**
     * @param: Object
     * @return Date
     * @author cui.guibin
     * @date 2019/3/21 19:51
     * 格式化时间
     */
    public static Date format2Date(Object timeStr){

        if (!Optional.ofNullable(timeStr).isPresent())
            return null;
        Date parse = null;
        if (timeStr instanceof String){
            try {
                parse = DF.get().parse((String) timeStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return parse;
    }
    /**
     * @param: Object
     * @return String
     * @author cui.guibin
     * @date 2019/3/21 19:51
     * 格式化时间
     */
    public static String format2String(Object str){

        if (!Optional.ofNullable(str).isPresent())
            return null;
        String parse = null;
        if (str instanceof String)
            parse = (String) str;

        return parse;
    }

    /**
     * 将时间戳转换成时间(date)
     * @param s
     * @return
     */
    public static Date stampToDate(String s){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return format2Date(res);
    }

    /**
     * 将时间戳转换成时间(String)
     * @param s
     * @return
     */
    public static String stampToString(String s){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }
}
